package com.zhang.study.chapter04;

import java.util.Arrays;

import static com.zhang.util.RandomArrayUtil.generateRandomArray;

/**
 * 逆序对问题
 * 在一个数组中，任何一个前面的数a，和任何一个后面的数b，如果(a,b)是降序的，就称为逆序对。返回数组中所有的逆序对个数
 */
public class Code05_InversePairByMergeSort {


    public static int inversePairs(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int mergeSize = 1;
        int res = 0;
        while (mergeSize < nums.length) {
            int left = 0;
            while (left < nums.length) {
                int mid = left + mergeSize - 1;
                if (mid >= nums.length) {
                    break;
                }
                int right = Math.min(left + (mergeSize << 1) - 1, nums.length - 1);
                res += merge(nums, left, mid, right);
                left = right + 1;
            }
            if (mergeSize > (nums.length >> 1)) {
                break;
            }
            mergeSize <<= 1;
        }
        return res;
    }
    private static int merge(int[] nums, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int k = 0;
        int res = 0;
        while (i <= mid && j <= right) {
            res += nums[i] > nums[j] ? (right - j+1) : 0;
            temp[k++] = nums[i] > nums[j] ? nums[i++] : nums[j++];
        }
        while (i <= mid) {
            temp[k++] = nums[i++];
        }
        while (j <= right) {
            temp[k++] = nums[j++];
        }
        for (k = 0; k < temp.length; k++) {
            nums[k + left] = temp[k];
        }
        return res;
    }

    public static int test(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++){
                if (nums[i] > nums[j]) {
                    res++;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 5;
        int maxValue = 100;
        System.out.println("test begin!");
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize, maxValue);
            int[] arr2 = Arrays.copyOf(arr1, arr1.length);
            if (inversePairs(arr1) != test(arr2)) {
                System.out.println("Oops!");
                System.out.println(Arrays.toString(arr1));
                System.out.println(Arrays.toString(arr2));
                break;
            }
        }
        System.out.println("test end!");
    }

}
